package com.rui.shangXueTang.linked;

/**
 * @author : [锐神NO.3]
 * @version : [v1.0]
 * @className : CircularLinkedList
 * @createTime : [2022/2/14 15:25]
 * @description : [单项环形链表]
 */

@SuppressWarnings("all")
public class CircularLinkedList {

    private Boy first = new Boy(-1);

    /**
     * 构建环形链表
     */
    public void addBoy(int nums){
        if(nums < 1){
            System.out.println("数据不正确");
        }

        Boy temp = null;

        for(int i = 1 ; i <= nums ; i++){
            Boy boy = new Boy(i);

            //判断是否是第一个小孩
            if(i == 1){
                first = boy;
                first.setNext(first);
                temp = first;
            }else {
                temp.setNext(boy);
                boy.setNext(first);
                temp = boy;
            }
        }
    }

    /**
     * 查看环形链表中的节点
     */
    public void showBoy(){
        if(first == null){
            System.out.println("链表为空");
            return;
        }

        Boy boy = first;

        while(true){
            System.out.println("小孩的编号: " + boy.getNo());
            if(boy.getNext() == first){
                break;
            }
            boy = boy.getNext();
        }
    }

    /**
     * 开始数数
     * @param startNo 开始编号
     * @param countNum 数几次
     * @param nums 链表中共有多少个节点
     */
    public void countBoy(int startNo, int countNum, int nums){
        if(first == null || startNo < 1 || startNo > nums){
            System.out.println("数据不正确");
            return;
        }

        //定义辅助节点，指向的是单链表中的最后一个节点
        Boy helper = first;

        while(true){
            if(helper.getNext() == first){
                break;
            }
            helper = helper.getNext();
        }

        //寻找起始位置 把first定义为起始位置
        for(int i = 0 ; i < startNo - 1 ; i++){
            first = first.getNext();
            helper = helper.getNext();
        }

        //当小孩进行报数时，数到m的孩子进行出列，只需让first和helper移动m-1次即可
        while(true){
            if(helper == first){
                break;
            }

            for(int i = 0 ; i < countNum - 1 ; i++){
                first = first.getNext();
                helper = helper.getNext();
            }

            System.out.println("小孩: " + first.getNo() + "出列");
            first = first.getNext();
            helper.setNext(first);
        }

        System.out.println("最后出圈的小孩: " + first.getNo());
    }
}
